const crypto = require('crypto');
//腾讯JSSDK签名
module.exports = class extends think.Service {
	createNonceStr() {
		return Math.random().toString(36).substr(2, 15);
	}

	createTimestamp() {
		return parseInt(new Date().getTime() / 1000) + '';
	}

	raw(args) {
		let keys = Object.keys(args);
		keys = keys.sort()
		let newArgs = {};
		keys.forEach(function(key) {
			newArgs[key.toLowerCase()] = args[key];
		});

		let string = '';
		for(let k in newArgs) {
			string += '&' + k + '=' + newArgs[k];
		}
		string = string.substr(1);
		return string;
	}

	/**
	 * @synopsis 签名算法 
	 *
	 * @param jsapi_ticket 用于签名的 jsapi_ticket
	 * @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
	 *
	 * @returns
	 */
	sign(jsapi_ticket, url) {
		let ret = {
			jsapi_ticket: jsapi_ticket,
			nonceStr: this.createNonceStr(),
			timestamp: this.createTimestamp(),
			url: url
		};
		let string = this.raw(ret);
		console.log(string);
		ret.signature = crypto.createHash('sha1').update(string).digest('hex');

		return ret;
	}
}